<?php

namespace App;

use \PDO;

class Db
{
    static public $dbpool = null;
    static private $type = [
        'string' => PDO::PARAM_STR,
        'integer' => PDO::PARAM_INT,
        'NULL' => PDO::PARAM_NULL,
        'boolean' => PDO::PARAM_BOOL,
    ];

    public function __construct($dbpool)
    {
        self::$dbpool = $dbpool;
    }

    // 预处理
    static private function pretreatment($pdo, $sql, $variable)
    {
        $statement = $pdo->prepare($sql);
        if (!empty($variable)) {
            foreach ($variable as $key => &$val) {
                $type = gettype($val);
                $statement->bindParam($key, $val, self::$type[$type]);
            }
        }
        $statement->execute();
        return $statement;
    }

    // 插入函数
    static public function insert(string $sql, array $variable = []): int
    {
        $pdo = self::$dbpool->get();
        self::pretreatment($pdo, $sql, $variable);
        $ret = $pdo->lastInsertId();
        self::$dbpool->put($pdo);
        return $ret;
    }

    // 更新函数
    static public function update(string $sql, array $variable = []): int
    {
        $pdo = self::$dbpool->get();
        $statement = self::pretreatment($pdo, $sql, $variable);
        $ret = $statement->rowCount();
        self::$dbpool->put($pdo);
        return $ret;
    }

    // 删除函数
    static public function delete(string $sql, array $variable = []): int
    {
        $pdo = self::$dbpool->get();
        $statement = self::pretreatment($pdo, $sql, $variable);
        $ret = $statement->rowCount();
        self::$dbpool->put($pdo);
        return $ret;
    }

    // 查询函数
    static private function fetch($sql, $variable, $fn = 'fetch')
    {
        $pdo = self::$dbpool->get();
        $statement = self::pretreatment($pdo, $sql, $variable);
        if ($fn === 'fetch') {
            $ret = $statement->fetch(PDO::FETCH_ASSOC);
        }
        if ($fn === 'fetchAll') {
            $ret = $statement->fetchAll(PDO::FETCH_ASSOC);
        }
        self::$dbpool->put($pdo);
        return $ret;
    }

    // 查询一条数据
    static public function get(string $sql, array $variable = []): array
    {
        return self::fetch($sql, $variable);
    }

    // 查询多条数据
    static public function all(string $sql, array $variable = []): array
    {
        return self::fetch($sql, $variable, 'fetchAll');
    }
}
